<template>
  <div id="mamageTemp">
    <el-container>
      <el-header class="main-head">
        <SearchRow :example="example" :name="name" :terms="terms"
          :queryAble="urls.list && $store.state.buttons[urls.list]"
          :addAble="urls.save && $store.state.buttons[urls.save]"></SearchRow>
      </el-header>
      <el-main class="app-main">
        <el-table :data="result.rows" :height="$store.state.sizes.pTableHei" border stripe>
          <el-table-column v-for="prop in props" v-if="!prop.tableHide" :prop="prop.code" :label="prop.name"
            :min-width="prop.width" :width="prop.type ? prop.width : ''" :type="prop.type"
            :formatter="(row,column,value) => getValue(prop.dict,value)" show-overflow-tooltip />
          <el-table-column v-if="urls.update || urls.del || actions" label="操作" :width="actionWidth" fixed="right">
            <template slot-scope="scope" v-if="!stateProp || scope.row[stateProp] != 'R'">
              <el-button v-if="urls.update && $store.state.buttons[urls.update]" size="mini" type="primary"
                @click="modify(scope.row)">
                修改 </el-button>
              <el-button v-if="urls.del && $store.state.buttons[urls.del]" size="mini" type="danger"
                @click="delate(scope.row)">
                删除 </el-button>
              <el-button v-for="action in actions" v-if="!action.url || $store.state.buttons[action.url]" size="mini"
                :type="action.type" @click="$emit(action.emit,scope.row)">{{action.name}}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination :current-page="example.page" :page-sizes="[10, 20, 50, 100]" :page-size="example.size"
          layout="total, sizes, prev, pager, next, jumper" :total="result.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-main>
    </el-container>

    <el-dialog :title="(flag.add ? '添加':'修改') + name" :visible.sync="flag.modify" :close-on-click-modal="false"
      top="15vh" :width="props.length > 8 ? '60%' : '40%'" @keydown.enter.native="confirm()">
      <el-form ref="update" class="full-item-form" label-width="180px" :rules="rules" :model="param">
        <el-row v-if="props.length > 8">
          <el-col :span="12" v-for="prop in props">
            <ModifyItem :prop="prop" :flag="flag" :param="param"></ModifyItem>
          </el-col>
        </el-row>
        <el-row v-else>
          <span v-for="prop in props">
            <ModifyItem :prop="prop" :flag="flag" :param="param"></ModifyItem>
          </span>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="flag.modify = false"> 取消 </el-button>
        <el-button type="primary" @click="confirm"> 确认 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    Vue,
    Component,
    Prop,
    Watch
  } from 'vue-property-decorator';
  import SearchRow from './searchRow.vue';
  import ModifyItem from './modifyItem.vue';

  @Component({
    components: {
      SearchRow,
      ModifyItem
    }
  })
  export default class MamageTemp extends Vue {
    @Prop({
      type: String
    }) name;

    @Prop({
      type: Object
    }) urls;

    @Prop({
      type: Array
    }) terms;

    @Prop({
      type: Array
    }) props;

    @Prop({
      type: Array
    }) actions;

    @Prop({
      type: Object
    }) rules;

    @Prop({
      type: String
    }) stateProp;

    actionWidth = 30;
    example = {
      page: 1,
      size: 20
    };
    result = {
      rows: [],
      total: 0
    };
    param = {};
    flag = {
      add: false,
      modify: false
    };

    handleSizeChange(val) {
      this.example.size = val
      this.query()
    }
    handleCurrentChange(val) {
      this.example.page = val
      this.query()
    }
    query(page) {
      const that = this
      if (page != null) {
        this.example.page = page
      }
      this.$get(that.urls.list, that.example).then(function(response) {
        if (response) {
          that.result = response
        } else {
          that.result = {
            rows: [],
            total: 0
          }
        }
      })
    }

    add() {
      if (this.$refs.update != null) {
        this.$refs.update.clearValidate()
      }
      this.param = {};
      this.flag.add = true
      this.flag.modify = true
    }
    modify(row) {
      if (this.$refs.update != null) {
        this.$refs.update.clearValidate()
      }
      this.flag.add = false
      this.param = JSON.parse(JSON.stringify(row))
      this.flag.modify = true
    }

    delate(row) {
      const that = this
      const msg = this.name ? this.name : "记录"
      this.$confirm('确定要删除该' + msg + '吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$post(that.urls.del, row).then(function(response) {
          if (response) {
            that.query()
            that.$emit('change');
          }
        })
      }).catch(() => {
        that.showMessage('info', '已取消删除')
      })
    }

    confirm() {
      const that = this
      this.$refs.update.validate((valid) => {
        if (valid) {
          const url = that.flag.add ? that.urls.save : that.urls.update;
          that.$post(url, that.param).then(function(response) {
            if (response) {
              that.query()
              that.flag.modify = false
              that.$emit('change');
            }
          })
        } else {
          return false
        }
      })
    }

    getValue(dictKey, value) {
      if (!dictKey) {
        return value;
      }
      const dict = this.$store.state.dict[dictKey]
      if (dict == null) {
        return value;
      }
      return dict[value] == null ? value : dict[value]
    }

    created() {
      this.query();
      if (this.urls.update) {
        this.actionWidth += 60;
      }
      if (this.urls.del) {
        this.actionWidth += 60;
      }
      const that = this;
      if (this.actions) {
        this.actions.forEach(i => {
          that.actionWidth += i.width;
        })
      }
    }

    @Watch('flag.modify')
    modifyChang(n, o) {
      if (!n) {
        this.param = {};
      }
    }

    mounted() {} // 生命周期 - 挂载完成（可以访问DOM元素）
    beforeCreate() {} // 生命周期 - 创建之前
    beforeMount() {} // 生命周期 - 挂载之前
    beforeUpdate() {} // 生命周期 - 更新之前
    updated() {} // 生命周期 - 更新之后
    beforeDestroy() {} // 生命周期 - 销毁之前
    destroyed() {} // 生命周期 - 销毁完成
    activated() {} // 如果页面有keep-alive缓存功能，这个函数会触发
  }
</script>
<style scoped>
  #mamageTemp {
    padding: 20px 20px 0px 20px;
  }
</style>
